﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Jzy.BLL.Project;
using Jzy.Core.Common;
using System.Data;
using Jzy.Model.Project;
using System.Web.UI.HtmlControls;
using Syncfusion.XlsIO;
using Frame.Lib.Web;
using Frame.Lib.Utilities;
using Frame.Lib.Common;

namespace Jzy.Web.Project.BugManage
{
    public partial class DoList : PageList
    {
        private PrjBugBO _bug = new PrjBugBO();
        private PagerSortSetting _setting;
        private int Status
        {
            get
            {

                //如果非返回，则清空session
                if (!IsReturn && !IsPostBack)
                {
                    Session["BugStatus"] = null;
                }

                if (Session["BugStatus"] == null)
                {
                    Session["BugStatus"] = -1;
                }

                return (int)Session["BugStatus"];
            }
            set
            {
                Session["BugStatus"] = value;
            }
        }

        /// <summary>
        /// 用于记录当前的页数
        /// </summary>
        private new  object PageIndex
        {
            get
            {
                //如果非返回，则清空session
                if (!IsReturn && !IsPostBack)
                {
                    Session["PageIndex"] = null;
                }

                return Session["PageIndex"];
            }
            set
            {
                Session["PageIndex"] = value;
            }
        }

        /// <summary>
        /// 是否通过返回按钮过来的
        /// </summary>
        private bool IsReturn
        {
            get
            {
                if (string.IsNullOrEmpty("IsReturn"))
                {
                    return false;
                }
                else
                {
                    try
                    {
                        return Convert.ToBoolean(Request["IsReturn"]);
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _setting = this.Pager1.InitPager(new BindViewHandler(BindView));
            if (!IsPostBack)
            {
                if (PageIndex != null)
                {
                    _setting.PageIndex = (int)PageIndex;
                }
                BindStatus();
                BindView();
            }
            AddAttr();
            InitSelectID(hidSelectIDs);
            JSUtil.SetTableHeight("list", 100);
        }
        private void AddAttr()
        {
            JSUtil.ClickBtn(lnkExport, btnExport);
        }

        private void BindStatus()
        {
            List<EnumInfo> list = ConvertUtil.ConvertEnum(typeof(BugStatus));

            EnumInfo info = new EnumInfo();
            info.ID = -1;
            info.Name = "全部";
            list.Insert(0, info);

            rptStatus.DataSource = list;
            rptStatus.DataBind();
        }
        protected void rptStatus_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Status = Convert.ToInt16(e.CommandArgument);
           
            BindView();
        }
        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            BindView();
        }

        private void BindView()
        {
            if (Status != -1)
            {
                lblStatus.Text = ((BugStatus)Status).ToString();
            }

            lv.DataKeyNames = new string[] { "ID", "Status" };
            InitLV(lv, lvHeader);
            // lv.EnableViewState = true;

            if (Status == -1)
            {
                pnlStatus.Visible = false;
            }
            else
            {
                pnlStatus.Visible = true;
            }

            List<PrjBugInfo> list = _bug.GetDoList(Status, AppSession.UserID);


            lv.DataSource = _setting.GetList<PrjBugInfo>(list);
            lv.DataBind();

            PageIndex = _setting.PageIndex;
        }

        protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                ListViewDataItem item = (ListViewDataItem)e.Item;
                string strEncryptID = StrUtil.EncryptUrl(lv.DataKeys[item.DataItemIndex]["ID"].ToString());
                HyperLink lnkDo = (HyperLink) e.Item.FindControl("lnkDo");
                string strUrl = GlobalVar.WebCurrPath + "DoBug.aspx?ID=" + strEncryptID;
                JSUtil.ShowForm(lnkDo, "处理缺陷", null, strUrl, 400, 230);

                HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("row");
                BugStatus status = (BugStatus)(int)lv.DataKeys[((ListViewDataItem)e.Item).DataItemIndex]["Status"];
                Label lblStatus = (Label)e.Item.FindControl("lblStatus");

                _bug.SetColorByStatus(lblStatus, status);
              

                HyperLink lnkName = (HyperLink)e.Item.FindControl("lnkName");
                HyperLink lnkDetail = (HyperLink)e.Item.FindControl("lnkDetail");
                lnkName.NavigateUrl = lnkDetail.NavigateUrl = "Detail.aspx?FromPage=" + (int)FromPage.DoList + "&ID=" + strEncryptID;

                HyperLink lnkChangeReceiver = (HyperLink)e.Item.FindControl("lnkChangeReceiver");
                strUrl = GlobalVar.WebCurrPath + "ChangeReceiver.aspx?ID=" + strEncryptID;
                JSUtil.ShowForm(lnkChangeReceiver, "重新指派缺陷处理人", null, strUrl, 400, 200);

                switch (status)
                {
                    case BugStatus.已关闭:
                        lnkDo.Enabled = lnkChangeReceiver.Enabled = false;
                        lnkDo.Attributes.Remove("onclick");
                        lnkChangeReceiver.Attributes.Remove("onclick");
                        break;
                    case BugStatus.已解决:
                        lnkChangeReceiver.Enabled = false;
                        lnkChangeReceiver.Attributes.Remove("onclick");
                        break;
                }
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (strSelectIDs == "")
            {
                JSUtil.Alert("请选择缺陷");
                BindView();
                return;
            }

            DataTable dt  = _bug.GetSelectData(strSelectIDs);

            ExcelEngine engine = new ExcelEngine();
            IApplication app = engine.Excel;
            IWorkbook book = app.Workbooks.Add();
            IWorksheet sheet = book.Worksheets[0];
            sheet.PageSetup.CenterHorizontally = true;
            sheet.PageSetup.Orientation = ExcelPageOrientation.Landscape;
            sheet.PageSetup.TopMargin = 0.5;
            sheet.PageSetup.LeftMargin = 0.5;
            sheet.PageSetup.RightMargin =0.5;
         


            sheet.Range[1, 1].Text = "缺陷标题";
            sheet.Range[1, 1].RowHeight = 15;
            sheet.Range[1, 1].ColumnWidth = 15;

            sheet.Range[1, 2].Text = "优先级";

            sheet.Range[1, 3].Text = "缺陷描述";
            sheet.Range[1, 3].ColumnWidth = 100;

            sheet.Range[1, 4].Text = "缺陷类型";

            sheet.Range[1, 5].Text = "期望完成日期";
            sheet.Range[1, 5].ColumnWidth = 15;

            sheet.Range[1, 1, 1, 5].CellStyle.Font.Bold = true;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                sheet.Range[i + 2, 1].Text = dr["Name"].ToString();

                sheet.Range[i + 2, 2].Text = ((BugPriority)(int)dr["Priority"]).ToString();
                sheet.Range[i + 2, 3].Text = dr["Remark"].ToString();
                sheet.Range[i + 2, 3].WrapText = true;
                sheet.Range[i + 2, 4].Text = dr["TypeName"].ToString();

                if (dr["PlanEndTime"] != DBNull.Value)
                {
                    sheet.Range[i + 2, 5].Text = ((DateTime)dr["PlanEndTime"]).ToString("yyyy-MM-dd");
                }

                sheet.Range[i + 2, 1, i + 2, 5].VerticalAlignment = ExcelVAlign.VAlignCenter;
            }

            for (int i = 1; i < dt.Rows.Count + 2; i++)
            {
                for (int j = 1; j < 6; j++)
                {
                    IRange range = sheet.Range[i, j];
                    IBorders border = range.CellStyle.Borders;

                    border.LineStyle = ExcelLineStyle.Thin;

                    border[ExcelBordersIndex.DiagonalDown].LineStyle = border[ExcelBordersIndex.DiagonalUp].LineStyle = ExcelLineStyle.None;
                }
            }

            book.SaveAs("bug.xls", ExcelSaveType.SaveAsXLS, Response, ExcelDownloadType.PromptDialog);
        }

    }

}
